package dao

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"order_srv/basic/config"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/models"
	"time"
)

// 优惠券创建
func CouponCreate(in *__.CouponCreateReq) (*models.Coupon, error) {
	var coupon models.Coupon
	var order models.Orders
	err := order.GetOrderInfo(int(in.OrderId))
	if err != nil {
		return nil, errors.New("订单查找失败")
	}
	if order.Id == 0 {
		return nil, errors.New("该订单不存在")
	}

	now := time.Now()
	coupon.CouponType = uint8(in.CouponType)
	coupon.Price = float64(in.Price)
	coupon.StartTime = now
	coupon.EndTime = now.Add(time.Hour * 24 * 7)
	coupon.UserId = uint64(order.UserId) // 优惠券用户
	coupon.OperatorId = in.OperatorId    // 优惠券操作人
	coupon.OrderId = in.OrderId          // 订单id
	if err := coupon.CreateCoupon(); err != nil {
		return nil, err
	}

	now = time.Now()
	month := now.Month()
	day := now.Day()
	content := fmt.Sprintf("%d月%d日从%v到%v的订单由客服赠送您一张%v元的优惠券，祝您旅途愉快!", month, day, order.StartLoc, order.EndLoc, in.Price)
	key := "coupon_" + fmt.Sprintf("%d", coupon.Id)
	marshal, err := json.Marshal(content)
	if err != nil {
		return nil, err
	}
	config.Rdb.Set(context.Background(), key, marshal, time.Hour*24)

	return &coupon, nil
}
